package com.platform.modules.chat.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.platform.common.constant.AppConstants;
import com.platform.modules.common.utils.Base64Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
public class ParseContent {
    private static String url = "https://api.textin.com/ai/service/v2/recognize";
    private static String appId = "e7ca367925cd6c68a08f8ed448dab4a4";
    private static String secretCode = "51861abc0d03c89cd22e92c7a0d9dd0b";
    public static byte[] readfile(String path) {
        String imgFile = path;
        InputStream in = null;
        byte[] data = null;
        try
        {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }
    public static String getResponse(String imgPath) {
        BufferedReader in = null;
        DataOutputStream out = null;
        String result = "";
        try {
            byte[] imgData = readfile(imgPath);
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            conn.setRequestProperty("x-ti-app-id", appId);
            conn.setRequestProperty("x-ti-secret-code", secretCode);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST"); // 设置请求方式
            out = new DataOutputStream(conn.getOutputStream());
            out.write(imgData);
            out.flush();
            out.close();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
    public static boolean generateBase64StringToFile(String fileBase64, String fileFilePath){
        if (fileBase64 == null) {//文件base64位数据为空
            return false;
        }
        try {
            File file = new File(fileFilePath);
            if (file.exists()) {
                return true;
            }
            //Base64解码
            byte[] b = org.apache.commons.codec.binary.Base64.decodeBase64(fileBase64);
            for(int i=0;i<b.length;++i) {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            //生成文件
            OutputStream out = new FileOutputStream(fileFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    private static String execCurl(String URL, String params) {
        StringEntity entity = new StringEntity(params, ContentType.APPLICATION_JSON);
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost request = new HttpPost(URL);
        request.setEntity(entity);
        HttpResponse response = null;
        try {
            response = httpClient.execute(request);
            if (response.getStatusLine().getStatusCode()==200) {
                String responseBody = EntityUtils.toString(response.getEntity());
                JSONObject json = JSON.parseObject(responseBody);
                System.out.println(json.get("data"));
                return json.get("data").toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    private static String getJsonImgContent(String uploadpath, String fileUrls, String messages) throws JSONException {
        String[] fileUrlAry = fileUrls.split("#");
        String[] messageAry = messages.split("#");
        JSONObject json = new JSONObject();
        String[] imgAry = new String[fileUrlAry.length];
        String[] historyAry = new String[messageAry.length-1];
        for (int i=0; i<fileUrlAry.length; i++) {
            String filePath = uploadpath + fileUrlAry[i];
            imgAry[i] = filePath;
        }
        for (int i=0; i<messageAry.length-1; i++) {
            if ("*".equals(messageAry[i])) {
                historyAry[i] = "";
            }else {
                historyAry[i] = messageAry[i];
            }
        }
        String curMessage = messageAry[messageAry.length-1];
        json.put("uuid", "34324141");
        json.put("img_paths", imgAry );
        json.put("prompt", curMessage);
        json.put("user_input", "");
        json.put("history", historyAry);
        json.put("is_image", "true");
        return json.toString();
    }
    private static String getJsonContent(String messages) throws JSONException {
        String[] messageAry = messages.split("#");
        JSONObject json = new JSONObject();
        String[] historyAry = new String[messageAry.length-1];
        for(int i=0; i<messageAry.length-1; i++){
            if ("*".equals(messageAry[i])) {
                historyAry[i] = "";
            }else {
                historyAry[i] = messageAry[i];
            }
        }
        String curMessage = messageAry[messageAry.length-1];
        json.put("uuid", "34324141");
        json.put("prompt", curMessage);
        json.put("history", historyAry);
        return json.toString();
    }
    public static String OCR(String fileBase64, String uploadpath, String messages, String fileUrls) {
        if (null==fileBase64) {
            String param = getJsonContent(messages);
            log.info(param);
            return execCurl("http://localhost:8000", param);
        }else {
            if (!"has".equals(fileBase64)) {
                String[] fileUrlAry = fileUrls.split("#");
                String filePath = uploadpath + fileUrlAry[fileUrlAry.length-1];
                generateBase64StringToFile(fileBase64, filePath);
            }
            String param = getJsonImgContent(uploadpath, fileUrls, messages);
            log.info(param);
            return execCurl("http://localhost:8000", param);
        }
    }

    public static String getFileBase64(String fileUrl) {
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try{
            in = new FileInputStream(AppConstants.DEFAULT_URL+fileUrl);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return Base64Util.getInstance().encode(data);
    }
}
